<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.rechargeExchange') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('rechargeExchange-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-input v-model="query.name" type="text" :placeholder="$t('table.ForeignLanguageName')" />
        </el-col>
        <el-col :span="4">
          <el-select v-model.number="query.status" :placeholder="$t('table.selectThe')+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="query.created_start"
            type="datetime"
            placeholder="开始日期时间"
            style="margin-left: 10px;"
          />
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="query.created_end"
            type="datetime"
            placeholder="结束日期时间"
            style="margin-left: 10px;"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
        <!-- 订单导出数据表 -->
        <el-col :span="3">
          <el-button type="danger" icon="el-icon-document" :disabled="!checkPermission('rechargeExchange-export')" @click="getSelected()">{{ $t('button.Excel') }}</el-button>
        </el-col>
      </el-row>

      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="550px" style="margin-top: 20px;" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column label="充值卡名称" prop="name" />
        <el-table-column label="卡号" prop="card_number" />
        <el-table-column prop="hexiao_code" label="核销码" />
        <el-table-column prop="money" label="充值金额" />
        <el-table-column label="赠送金额" prop="give" />
        <el-table-column label="赠送积分" prop="give_score" />
        <el-table-column label="绑定人ID" prop="mid" />
        <el-table-column :label="$t('table.state')" prop="status" width="120">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|ExchangeStatusData }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="有效期至" prop="end_time">
          <template slot-scope="{row}">
            {{ row.end_time|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="220" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('rechargeExchange-edit')" @click="addOrEidt('edit',row)">{{ $t('button.edit') }}</el-button>

            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('rechargeExchange-del')" @click="delData(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
        <el-form-item label="充值卡名称">
          <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+'充值卡名称'" style="width:50%" />
        </el-form-item>
        <el-form-item label="绑定人id">
          <el-input v-model.number="formData.mid" :placeholder="$t('table.enterThe')+'绑定人id'" style="width:50%" />
        </el-form-item>
        <el-form-item v-if="type===1" label="新增数量">
          <el-input v-model.number="formData.num" :placeholder="$t('table.enterThe')+'新增数量'" style="width:50%" />
        </el-form-item>
        <el-form-item label="充值金额">
          <el-input v-model.number="formData.money" :placeholder="$t('table.enterThe')+'充值金额'" style="width:50%" />
        </el-form-item>
        <el-form-item label="赠送金额">
          <el-input v-model.number="formData.give" :placeholder="$t('table.enterThe')+'赠送金额'" style="width:50%" />
        </el-form-item>
        <el-form-item label="赠送积分">
          <el-input v-model.number="formData.give_score" :placeholder="$t('table.enterThe')+'赠送积分'" style="width:50%" />
        </el-form-item>
        <el-form-item label="有效时间">
          <el-date-picker
            v-model.number="formData.start_time"
            type="datetime"
            placeholder="开始时间"
            value-format="timestamp"
            style="margin-left: 10px;width:40%"
          />-
          <el-date-picker
            v-model.number="formData.end_time"
            type="datetime"
            placeholder="结束时间"
            value-format="timestamp"
            style="margin-left: 10px;width:40%"
          />
        </el-form-item>
        <el-form-item label="后台备注">
          <el-input v-model="formData.remark" :placeholder="$t('table.enterThe')+'后台备注'" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.state')">
          <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { RechargeExchangeList, RechargeExchangeAdd, RechargeExchangeDel } from '@/api/user'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'warning',
        3: 'danger',
        5: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 5,
        value: '未生效'
      },
      {
        id: 1,
        value: '未兑换'
      },
      {
        id: 2,
        value: '已兑换'
      },
      {
        id: 3,
        value: '失效'
      }],
      query: {
        status: undefined,
        name: '',
        aid: 1,
        created_start: '',
        created_end: '',
        page: 1,
        limit: 10
      },
      count: 0,
      dialogTitle: this.$t('button.add'),
      type: 1,
      formData: {
        aid: 1,
        id: undefined,
        name: '',
        mid: undefined,
        status: undefined,
        card_number: '',
        money: undefined,
        give: undefined,
        give_score: undefined,
        start_time: undefined,
        end_time: undefined,
        remark: '',
        num: undefined
      },
      rules: {
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false,
      multipleSelection: []
    }
  },
  created() {
    // 获取userid
    this.getBusinessCateList()
  },
  methods: {
    // 保存选择对象
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取选中数据,导出excel
    async getSelected() {
      const headers = {
        '充值卡名称': 'name',
        '充值卡编号': 'card_number',
        '核销码': 'hexiao_code',
        '充值金额': 'money',
        '赠送金额': 'give',
        '赠送积分': 'give_score'
      }
      const ordernum = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const one = {
          name: this.multipleSelection[i].name,
          card_number: this.multipleSelection[i].card_number,
          hexiao_code: this.multipleSelection[i].hexiao_code,
          money: this.multipleSelection[i].money,
          give: this.multipleSelection[i].give,
          give_score: this.multipleSelection[i].give_score
        }
        ordernum.push(one)
      }
      const data = this.formatJson(headers, ordernum)
      // 导出Excel
      import('@/vendor/Export2Excel').then(excel => {
        // excel是引入文件的导出对象
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: data,
          filename: '充值卡信息'
        })
      })
    },
    // 将表头数据和数组进行对应
    formatJson(headers, rows) {
      return rows.map(item => {
        // item 是一个对象
        return Object.keys(headers).map(key => {
          return item[headers[key]]
        })
      })
    },
    // 获取商户分了列表
    async getBusinessCateList() {
      this.downloadLoading = true
      const { count, list } = await RechargeExchangeList(this.query)
      this.count = count
      this.list = list
      this.downloadLoading = false
    },
    // 点击展开新增修改
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('button.add')
        this.type = 1
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('button.edit')
        this.type = 2
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.status = row.status
        this.formData.mid = row.mid
        this.formData.card_number = row.card_number
        this.formData.money = row.money
        this.formData.give = row.give
        this.formData.give_score = row.give_score
        if (row.start_time > 0) {
          this.formData.start_time = row.start_time * 1000
        }
        if (row.start_time > 0) {
          this.formData.end_time = row.end_time * 1000
        }
        this.formData.remark = row.remark
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        // 调用新增接口
        await RechargeExchangeAdd(this.formData)
        // 更新数据
        this.getBusinessCateList()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除管理员
    async delData(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await RechargeExchangeDel(data)
        this.getBusinessCateList()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        aid: 1,
        id: undefined,
        name: '',
        mid: undefined,
        status: undefined,
        card_number: '',
        money: undefined,
        give: undefined,
        give_score: undefined,
        start_time: undefined,
        end_time: undefined,
        remark: '',
        num: undefined
      }
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getBusinessCateList()
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getBusinessCateList()
    }
  }
})
</script>
<style lang="scss">
.table-img{
  width: 90px;
}
</style>
